const query = require('../../dbConfig/index')
const {camelCase} = require('../../utils/utils')
const { generateToken } = require('../../utils/middleware')
const get = async (ctx,next)=>{
	const body = ctx.request.body
	const offset = (body.pageNumber - 1) * Number(body.pageSize);  
	let sql = 'SELECT * FROM speciality';  
	let params = [];  
	// 如果传了条件 就拼接sql
	if (body.specialityName && body.specialityName.trim() !== '') {  
		sql += ' WHERE speciality_name=?';  
		params.push(body.specialityName);  
	  }  
	  sql += ' LIMIT ? OFFSET ?';  
	  params.push(Number(body.pageSize));  
	  params.push(offset);
	const res = await query(sql,params)
	const total = await query(`SELECT COUNT(*) as total FROM speciality`)
	if(res.length>0){
		ctx.body={code:200,data:{records:camelCase(res),total:total[0].total},msg:'成功'}
		next()
	}else{
		ctx.body={code:0,data:null,msg:'暂无专业数据'}
	}
}
const updata = async (ctx,next)=>{
	const body = ctx.request.body
	if(!body.specialityName && !body.specialityDescription){
		ctx.body={code:0,data:null,msg:'缺少数据'}
		return
	}
	await query(`UPDATE speciality SET speciality_name = ?,speciality_description=? WHERE speciality_id='${body.specialityId}'`,[body.specialityName,body.specialityDescription])
	ctx.body={code:200,data:null,msg:'成功'}
	next()
	
}
const add = async (ctx,next)=>{
	const body = ctx.request.body
	await query(`INSERT INTO speciality (speciality_name, speciality_description) VALUES (?, ?)`,[body.specialityName,body.specialityDescription])
	ctx.body={code:200,data:null,msg:'成功'}
	next()
}
const remove = async (ctx,next)=>{
	const body = ctx.request.body
	await query(`DELETE FROM speciality WHERE speciality_id=${body.id}`)
	ctx.body={code:200,data:null,msg:'成功'}
	next()
}
module.exports = {
	get,
	add,updata,remove
}